<template>
  <el-container class="home-container">
    <el-main>
      <el-card>
        <template #header>
          <h1>欢迎来到我们的在线商店！</h1>
        </template>
        <p>在这里，您可以浏览我们精选的商品，将它们添加到购物车，并轻松下单。</p>
        <p>
          <el-button type="primary" @click="goToProducts">开始购物</el-button>
        </p>
        
        <el-divider />
        
        <div v-if="recommendedProducts.length > 0" class="recommended-section">
          <h2>推荐商品</h2>
          <el-row :gutter="20">
            <el-col
              v-for="product in recommendedProducts"
              :key="product.id"
              :xs="24" :sm="12" :md="8" :lg="6"
              class="product-col"
            >
              <el-card shadow="hover" class="product-card">
                <img 
                  :src="product.thumbnail_url || 'https://via.placeholder.com/300x200.png?text=No+Image'" 
                  class="product-image" 
                  alt="商品图片"
                  @click="goToProductDetail(product.slug)"
                />
                <div class="product-info">
                  <h3 class="product-name" @click="goToProductDetail(product.slug)">
                    {{ product.name }}
                  </h3>
                  <p class="product-price">¥ {{ product.price }}</p>
                  <el-button type="warning" plain size="small" @click="addToCart(product)">
                    <el-icon><ShoppingCart /></el-icon> 添加到购物车
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import productService from '../api/product.service';
import cartService from '../api/cart.service'; // 引入购物车服务
import { ElMessage } from 'element-plus';
//ShoppingCart图标已经全局注册，无需单独引入

const router = useRouter();
const recommendedProducts = ref([]);

const goToProducts = () => {
  router.push({ name: 'Products' });
};

const goToProductDetail = (slug) => {
  router.push({ name: 'ProductDetail', params: { slug } });
};

const fetchRecommendedProducts = async () => {
  try {
    // 获取推荐商品，可以调整参数，例如每页数量
    const response = await productService.getProducts({ is_recommended: true, limit: 4 });
    recommendedProducts.value = response.data; // 后端返回的数据结构是 { data: [], meta: {}, links: {} }
  } catch (error) {
    console.error('获取推荐商品失败:', error);
    ElMessage.error('获取推荐商品失败');
  }
};

const addToCart = async (product) => {
  try {
    await cartService.addItem({ product_id: product.id, quantity: 1 });
    ElMessage.success(`${product.name} 已添加到购物车`);
  } catch (error) {
    console.error('添加到购物车失败:', error);
    const errorMessage = error.message || '添加到购物车失败';
    ElMessage.error(errorMessage);
  }
};

onMounted(() => {
  fetchRecommendedProducts();
});
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.recommended-section {
  margin-top: 30px;
}

.product-col {
  margin-bottom: 20px;
}

.product-card {
  cursor: pointer;
}

.product-image {
  width: 100%;
  height: 200px; /* 固定高度，可根据需要调整 */
  object-fit: cover; /* 保持图片比例并填充 */
  display: block;
}

.product-info {
  padding: 14px;
  text-align: left;
}

.product-name {
  font-size: 16px;
  margin: 10px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  color: #ff4d4f;
  font-size: 18px;
  margin-bottom: 10px;
}
</style> 